package von.seiji.cn.imageT;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import org.junit.Test;
import org.opencv.core.*;

import static org.opencv.highgui.HighGui.*;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.net.MalformedURLException;
import java.net.URL;

public class 模板匹配和边缘检测 {

    static {
        URL systemResource = ClassLoader.getSystemResource("data/opencv_java454.dll");
        System.out.println("systemResource.getPath() = " + systemResource.getPath());
        System.load(systemResource.getPath());

    }

    /**
     * 图片模板位置识别
     *
     * @param args
     */
    public static void main(String[] args) {

        Mat source, template;
        //将文件读入为OpenCV的Mat格式
        source = Imgcodecs.imread("C:\\Users\\Administrator\\Desktop\\temp\\payment\\321.jpg");
        template = Imgcodecs.imread("C:\\Users\\Administrator\\Desktop\\temp\\payment\\132.jpg");
        //创建于原图相同的大小，储存匹配度
        Mat result = Mat.zeros(source.rows() - template.rows() + 1, source.cols() - template.cols() + 1, CvType.CV_32FC1);
        //调用模板匹配方法
        Imgproc.matchTemplate(source, template, result, Imgproc.TM_SQDIFF_NORMED);
        //规格化
        Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1);
        //获得最可能点，MinMaxLocResult是其数据格式，包括了最大、最小点的位置x、y
        Core.MinMaxLocResult mlr = Core.minMaxLoc(result);
        Point matchLoc = mlr.minLoc;
        //在原图上的对应模板可能位置画一个绿色矩形
        Imgproc.rectangle(source, matchLoc, new Point(matchLoc.x + template.width(), matchLoc.y + template.height()), new Scalar(0, 255, 0));
        //将结果输出到对应位置
//        Imgcodecs.imwrite("C:\\Users\\Administrator\\Desktop\\temp\\payment\\匹配结果132.jpg", source);
        imshow("L", source);
        waitKey(0);

        System.out.println("+++++");
    }


    /**
     * 边缘检测
     *
     *  必须得用这个opencv_java454.dll！！！
     * @param frame
     * @return
     */
    private Mat doCanny(Mat frame) {
        // init
        Mat grayImage = new Mat();

        Mat detectedEdges = new Mat();

        // convert to grayscale
        Imgproc.cvtColor(frame, grayImage, Imgproc.COLOR_BGR2GRAY);

        // reduce noise with a 3x3 kernel
        Imgproc.blur(grayImage, detectedEdges, new Size(3, 3));
//        imshow("L2", detectedEdges.clone());

        // canny detector, with ratio of lower:upper threshold of 3:1
        double threshold = 18;

        // Canny边缘检测器检测图像边缘

        Imgproc.Canny(detectedEdges, detectedEdges, threshold, threshold * 3, 3);
        imshow("L3", detectedEdges);

        // using Canny's output as a mask, display the result
        Mat dest = new Mat();
        dest.create(frame.size(), frame.type());
        dest.setTo(Scalar.all(255));
        frame.copyTo(dest, detectedEdges);

        //再来一个
      /*  Mat imread = Imgcodecs.imread("C:\\Users\\Administrator\\Desktop\\temp\\pic\\yaya.jpg");
        Mat clone = new Mat(imread.rows(), imread.cols(), imread.type());
        Imgproc.cvtColor(imread,clone, Imgproc.COLOR_RGB2GRAY);
        lkdla(clone);
//        imshow("mask", clone);
        Mat submat = dest.submat(new Rect(20, 50, imread.width(), imread.height()));
        imread.copyTo(submat, clone);*/
        return dest;
    }

    public void lkdla(Mat mat) {
        for (int i = 0; i < mat.rows(); i++) {
            for (int i1 = 0; i1 < mat.cols(); i1++) {
                mat.put(i, i1, new double[] {255 - mat.get(i, i1)[0]});
            }
        }
    }


    @Test
    public void alf() throws MalformedURLException {

        String url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202008%2F29%2F20200829130145_anbvf.thumb.400_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1644050338&t=a7da518629fb683155578685e80a9f2d";

        byte[] bytes = IoUtil.readBytes(URLUtil.getStream(new URL(url)));
        Mat source = Imgcodecs.imdecode(new MatOfByte(bytes), Imgcodecs.IMREAD_COLOR);

//        Mat source = Imgcodecs.imread("C:\\Users\\Administrator\\Pictures\\5e766b9a767c4a7eb8e26f4ab611cab.jpg");

        imshow("L0", source);
        Mat mat = doCanny(source);
        imshow("LL", mat);
//        Imgcodecs.imwrite("C:\\Users\\Administrator\\Pictures\\sss.jpg", mat);
        waitKey(0);
    }

    @Test
    public void dlsafj() {

    }

}